package cn.com.shadowless.xinning.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.mengpeng.mphelper.ToastUtils;

import java.text.DecimalFormat;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.bill.BillListInfo;
import cn.com.shadowless.xinning.model.order.CheckHistoryList;
import cn.com.shadowless.xinning.presenter.BillPresenter;
import cn.com.shadowless.xinning.presenter.LoginPresenter;
import cn.com.shadowless.xinning.presenter.OrderPresenter;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.view.activity.LoginActivity;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * The type Base fragment.
 *
 * @author sHadowLess
 */
public abstract class BaseFragment extends Fragment {

    /**
     * The M activity.
     */
    protected final String TAG = BaseFragment.class.getSimpleName();
    /**
     * The M activity.
     */
    protected Activity mActivity;
    /**
     * The Composite disposable.
     */
    protected CompositeDisposable compositeDisposable;

    /**
     * 获得全局的，防止使用getActivity()为空
     *
     * @param context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(mActivity).inflate(getLayoutId(), container, false);
        ButterKnife.bind(this, view);
        compositeDisposable = new CompositeDisposable();
        initData();
        initView();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        if (!compositeDisposable.isDisposed()) {
            compositeDisposable.dispose();
        }
        Log.e(TAG, "onDestroyView: " + "已销毁");
        super.onDestroyView();
    }

    /**
     * 该抽象方法就是 onCreateView中需要的layoutID
     *
     * @return layout id
     */
    protected abstract int getLayoutId();

    /**
     * 执行数据的加载
     */
    protected abstract void initData();

    /**
     * Init view.
     */
    protected abstract void initView();

    /**
     * Init check history list.
     *
     * @param url           the url
     * @param mActivity     the m activity
     * @param mLinearLayout the m linear layout
     */
    protected void initCheckHistoryList(String url, Activity mActivity, LinearLayout mLinearLayout) {
        String userName = PreferencesUtils.getString(MyApplication.getInstance(), "userName", "-1");
        OrderPresenter.getSingleton().getCheckHistoryList(url, userName, new RequestCallBack<CheckHistoryList>() {
            @Override
            public void success(RequestResult<CheckHistoryList> result) {
                String token = result.getLoginToken();
                String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                if (result.isSucceed() && null != result.getResult()) {
                    if (null != token && token.equals(oldToken)) {
                        Log.e(TAG, "success: " + result.toString());
                        List<CheckHistoryList.DataBean> dataBean = result.getResult().getData();
                        for (int i = 0; i < dataBean.size(); i++) {
                            View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_order_process_item, null, false);
                            LinearLayout linearLayout = view.findViewById(R.id.general_check_Process_Item);
                            TextView time = view.findViewById(R.id.general_check_Process_Time);
                            TextView link = view.findViewById(R.id.general_check_Process_Link);
                            TextView name = view.findViewById(R.id.general_check_Process_Name);
                            TextView status = view.findViewById(R.id.general_check_Process_Status);
                            String checkTimeStr = dataBean.get(i).getCheckTimeStr();
                            String checkAccountUserName = dataBean.get(i).getCheckAccountUserName();
                            String processName = dataBean.get(i).getProcessName();
                            String statusStr = dataBean.get(i).getStatusStr();
                            time.setText(checkTimeStr);
                            name.setText(String.format("%s(%s)", checkAccountUserName, processName));
                            status.setText(statusStr);
                            if ("待审核".equals(statusStr)) {
                                time.setTextColor(Color.parseColor("#4a80ef"));
                                link.setTextColor(Color.parseColor("#4a80ef"));
                                name.setTextColor(Color.parseColor("#4a80ef"));
                                status.setTextColor(Color.parseColor("#4a80ef"));
                            }
                            mLinearLayout.addView(linearLayout);
                        }
                    } else {
                        ToastUtils.onErrorShowToast("错误代码：" + result.getErrorCode() + "\n错误信息：" + result.getRemark());
                        initLogoutInfo(mActivity, userName);
                    }
                } else {
                    ToastUtils.onErrorShowToast("暂无审批流程信息");
                }
            }

            @Override
            public void fail(String errorMsg) {
                ToastUtils.onErrorShowToast(errorMsg);
            }
        });
    }

    /**
     * Init logout info.
     *
     * @param activity the activity
     */
    public static void initLogoutInfo(Activity activity, String userName) {
//        if (null == userName) {
//            userName = PreferencesUtils.getString(MyApplication.getInstance(), "userName", "-1");
//        }
//        if (!"-1".equals(userName)) {
//            LoginPresenter
//                    .getSingleton()
//                    .getLogoutInfo(userName, new RequestCallBack<RequestResult<Object>>() {
//                        @Override
//                        public void success(RequestResult<RequestResult<Object>> result) {
//                            if (result.isSucceed()) {
//                                ToastUtils.onSuccessShowToast("退出成功");
        Observable
                .timer(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(aLong -> {
                    activity.startActivity(new Intent(activity, LoginActivity.class));
                    activity.finish();
                });
//                            } else {
//                                ToastUtils.onSuccessShowToast("退出失败，请关闭应用");
//                            }
//                        }
//
//                        @Override
//                        public void fail(String errorMsg) {
//                            ToastUtils.onErrorShowToast(errorMsg);
//                        }
//                    });
//        }
    }

    public static void initLogoutInfo1(Activity activity, String userName) {
        if (null == userName) {
            userName = PreferencesUtils.getString(MyApplication.getInstance(), "userName", "-1");
        }
        if (!"-1".equals(userName)) {
            LoginPresenter
                    .getSingleton()
                    .getLogoutInfo(userName, new RequestCallBack<RequestResult<Object>>() {
                        @Override
                        public void success(RequestResult<RequestResult<Object>> result) {
                            if (result.isSucceed()) {
                                ToastUtils.onSuccessShowToast("退出成功");
                                PreferencesUtils.clear(MyApplication.getInstance());
                                activity.startActivity(new Intent(activity, LoginActivity.class));
                                activity.finish();
                            } else {
                                ToastUtils.onSuccessShowToast("退出失败，请关闭应用");
                            }
                        }

                        @Override
                        public void fail(String errorMsg) {
                            ToastUtils.onErrorShowToast(errorMsg);
                        }
                    });
        }
    }


    protected String getDecimal(double num) {
        DecimalFormat df1 = new DecimalFormat("0.000");
        return df1.format(num);
    }
}
